package cn.py.boot_lua.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;

public class DowFileUtil {
    private static final Logger log = LoggerFactory.getLogger(DowFileUtil.class);
    public static Boolean downloadFile(String fileURL, String savePath){
        try {
            URL url = new URL(fileURL);
            HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
            int responseCode = httpConn.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                BufferedInputStream in = new BufferedInputStream(httpConn.getInputStream());
                FileOutputStream out = new FileOutputStream(savePath);
                byte[] buffer = new byte[1024];
                int bytesRead = -1;
                while ((bytesRead = in.read(buffer)) != -1) {
                    out.write(buffer, 0, bytesRead);
                }
                out.close();
                in.close();
                log.info("保存路径: " + savePath);
                return true;
            } else {
                log.info("下载失败: " + responseCode);
            }
            //终止HTTP连接
            httpConn.disconnect();
        } catch (IOException e) {
            throw new RuntimeException("文件下载失败");
        }
        return false;
    }

    public static byte[] dowFileAsBytes(String fileURL) {
        try {
            URL url = new URL(fileURL);
            HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
            int responseCode = httpConn.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                InputStream in = httpConn.getInputStream();
                ByteArrayOutputStream out = new ByteArrayOutputStream();
                byte[] buffer = new byte[1024];
                int bytesRead = -1;
                while ((bytesRead = in.read(buffer)) != -1) {
                    out.write(buffer, 0, bytesRead);
                }
                // 关闭流
                in.close();
                out.close();
                // 返回字节数组
                return out.toByteArray();
            } else {
                log.info("下载失败，响应码: " + responseCode);
            }
            // 终断连接
            httpConn.disconnect();
        } catch (IOException e) {
            throw new RuntimeException("文件下载失败", e);
        }
        return null;
    }

}
